package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 攻略分类接口实现类
 */
@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;
    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;
    @Autowired
    private IStrategyService strategyService;


    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        return strategyCatalogRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return strategyCatalogRepository.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {

        //查询对象
        Query query = new Query();
        //查询总数
        long totalCount = template.count(query, StrategyCatalog.class);
        if (totalCount == 0) {
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        return new PageImpl<>(list, pageable, totalCount);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        //判断是否带id
        if (StringUtils.hasLength(strategyCatalog.getId())) {
            //有则编辑
            this.update(strategyCatalog);
        } else {
            //无则添加
            this.save(strategyCatalog);
        }
    }


    @Override
    public List<CatalogVO> groupList() {
        //先创建一个集合，用于存储数据
        List<CatalogVO> list = new ArrayList<>();
        //mongodb 聚合查询，在Java中
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        //遍历
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());//设置目的地名字
            List<Object> names = (List<Object>) data.get("names");//攻略分类名字集合
            List<Object> ids = (List<Object>) data.get("ids");//攻略分类id集合
            //创建一个攻略分类集合
            List<StrategyCatalog> catalogList = new ArrayList<>();
            for (int i = 0; i < names.size(); i++) {
                StrategyCatalog sc = new StrategyCatalog();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                sc.setId(id);
                sc.setName(name);
                catalogList.add(sc);

            }
            vo.setCatalogs(catalogList);//设置攻略分类集合元素
            list.add(vo);//将vo数据添加到集合中
        }
        System.out.println(list);
        return list;
    }

    @Override
    public List<StrategyCatalog> queryCatalogByDestId(String destId) {
        //所有指定目的地id下的攻略分类
        List<StrategyCatalog> list = strategyCatalogRepository.findByDestId(destId);
        for (StrategyCatalog strategyCatalog : list) {
            List<Strategy> strategies = strategyService.queryCatalogId(strategyCatalog.getId());
            strategyCatalog.setStrategies(strategies);
        }
        return list;
    }
}
